

package com.hit.common.security.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hit.admin.api.dto.UserDTO;
import com.hit.admin.api.dto.UserInfo;
import com.hit.admin.api.entity.SysUser;
import com.hit.admin.api.service.SysUserService;
import com.hit.common.core.constant.CacheConstants;
import com.hit.common.core.constant.SecurityConstants;
import com.hit.common.core.exception.ErrorCodes;
import com.hit.common.core.util.MsgUtils;
import com.hit.common.core.util.R;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 用户详细信息
 *
 * @author kehanjiang hccake
 */
@Slf4j
@RequiredArgsConstructor
public class HitAppUserDetailsServiceImpl implements HitUserDetailsService {

	private final SysUserService userService;

	private final CacheManager cacheManager;

	/**
	 * 手机号登录
	 * @param phone 手机号
	 * @return
	 */
	@Override
	@SneakyThrows
	public UserDetails loadUserByUsername(String phone) {
		Cache cache = cacheManager.getCache(CacheConstants.USER_DETAILS);
		if (cache != null && cache.get(phone) != null) {
			return (HitUser) cache.get(phone).get();
		}

		UserDTO userDTO = new UserDTO();
		userDTO.setPhone(phone);
		R<UserInfo> result = this.info(userDTO);

		UserDetails userDetails = getUserDetails(result);
		if (cache != null) {
			cache.put(phone, userDetails);
		}
		return userDetails;
	}

	private R<UserInfo> info(UserDTO userDTO) {
		String username = userDTO.getUsername();
		String phone = userDTO.getPhone();
		SysUser user = userService.getOne(Wrappers.<SysUser>query()
				.lambda()
				.eq(StrUtil.isNotBlank(username), SysUser::getUsername, username)
				.eq(StrUtil.isNotBlank(phone), SysUser::getPhone, phone));
		if (user == null) {
			return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_USER_USERINFO_EMPTY, username));
		}
		return R.ok(userService.findUserInfo(user));
	}
	/**
	 * check-token 使用
	 * @param hitUser user
	 * @return
	 */
	@Override
	public UserDetails loadUserByUser(HitUser hitUser) {
		return this.loadUserByUsername(hitUser.getPhone());
	}

	/**
	 * 是否支持此客户端校验
	 * @param clientId 目标客户端
	 * @return true/false
	 */
	@Override
	public boolean support(String clientId, String grantType) {
		return SecurityConstants.MOBILE.equals(grantType);
	}

}
